package me.xplabs.engine 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.utils.getTimer;
	
	/**
	 * http://www.xplabs.me/
	 * @author xiaohan
	 */
	public class Animation extends Bitmap 
	{
		protected var _bitmaps:Vector.<BitmapData>;
		protected var _frameIndex:int;
		public var repeat:Boolean;
		public var playOver:Function;
		public var isPlaying:Boolean;
		protected var _gap:int;
		protected var _prev:uint;
		protected var totalFrame:uint;
		public var speed:int;
		public var object:Object;
		
		
		public var curPosX:Number;
		public var curPosY:Number;
		public function Animation() 
		{
			_bitmaps = new Vector.<BitmapData>();
			isPlaying = false;
			this.repeat = true;
			speed = 100;
		}
		public function addBitmap(p_bitmapData:BitmapData):void
		{
			_bitmaps.push(p_bitmapData);
		}
		public function setBitmaps(bitmaps:Vector.<BitmapData>,repeat:Boolean = true):void
		{
			_bitmaps = bitmaps;
			this.repeat = repeat;
		}
		public function play(speed:int = 100):void
		{
			isPlaying = true;
			_frameIndex = 0;
			_prev = 0;
			totalFrame = 0;
			this.speed = speed;
		}
		public function update():void
		{
			if (!isPlaying) return;
			if (_bitmaps.length <= 0) return;
			var now:uint = getTimer() - _prev;
			_prev = getTimer();
			totalFrame += now;
			_gap = totalFrame / speed;
			if (_gap < 1) return;
			totalFrame -= _gap * speed;
			_frameIndex += _gap;
			var len:int = _bitmaps.length;
			if (_gap >= len) _frameIndex = 0;
			if (_frameIndex >= len)
			{
				if (repeat) _frameIndex = 0;
				else 
				{
					if (playOver != null) 
					{
						playOver(this);
						return;
					}
				}
			}
			bitmapData = _bitmaps[_frameIndex];
			if (bitmapData)
			{
				if (bitmapData.hasOwnProperty("x") && bitmapData.hasOwnProperty("y"))
				{
					x = curPosX - bitmapData["x"];
					y = curPosY - bitmapData["y"];
				}else
				{
					x = curPosX - bitmapData.width * .5;
					y = curPosY - bitmapData.height * .5;
				}
			}
		}

		public function stop():void
		{
			isPlaying = false;
		}
		
		public function dispose():void
		{
			//var len:int = _bitmaps.length;
			//for (var i:int = 0; i < len; i++) 
			//{
				//_bitmaps[i].dispose();
			//}
			bitmapData = null;
			_bitmaps.length = 0;
			isPlaying = false;
			rotation = 0;
			this.repeat = true;
			playOver = null;
			speed = 100;
			x = 0;
			y = 0;
			object = null;
		}
	}

}